package com.lx.vcode.web;

import com.lx.bean.Result;
import com.lx.vcode.bean.VcodePropertise;
import com.lx.vcode.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;

@RestController
@RequestMapping("vcode")
public class VcodeDo {

    @Autowired
    VcodePropertise vcodePropertise;

    @GetMapping("config")
    VcodePropertise vcodePropertise(){
        return vcodePropertise;
    }
                                        // MediaType 设定返回值的类型
    @RequestMapping(path = "image", produces = MediaType.IMAGE_PNG_VALUE)
    public void image(HttpServletResponse response, HttpSession session) throws IOException {
        // 生成验证码图片返回给浏览器
        String vcode = VerifyCodeUtils.outputImage((javax.servlet.http.HttpServletResponse) response);
        session.setAttribute("vcode", vcode);

        long time = System.currentTimeMillis();
        time += vcodePropertise.getTimeout() * 1000;
        session.setAttribute("vcode-timeout", time);
    }


    @Autowired
    MailSender mailSender;


    // TODO 定义发送验证码邮件的方法, 提供给未来的控制器方法调用即可

    @GetMapping("email")
    public Result email(String email, String msgName, HttpSession session){

        String vcode = System.currentTimeMillis()+"";
        vcode = vcode.substring(vcode.length() - 4);
        session.setAttribute("vcode", vcode);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(email);
        message.setFrom(vcodePropertise.getFromEmail());
        message.setSubject("验证码");
        // 编辑邮件信息
        message.setText(String.format(vcodePropertise.getMsgs().get(msgName), vcode));
        mailSender.send(message);
        long time = System.currentTimeMillis();
        time += vcodePropertise.getTimeout() * 1000;
        session.setAttribute("vcode-timeout", time);
        return new Result(1, "验证码发送成功", null);
    }
}
